<template>
  <div class="properties-page">
    <el-container>
      <el-header class="page-header">
        <div class="brand">
          <img class="brand-logo" src="/favicon.ico" alt="logo" />
          <h2>优选好房</h2>
        </div>
        <div class="subtitle">真实在租 · 新鲜上新 · 品质甄选</div>
      </el-header>

      <el-main>
        <el-card class="filter-card" shadow="never">
          <el-form :model="filters" inline label-width="80px" class="filter-form">
            <el-form-item label="关键词">
              <el-input v-model="filters.keyword" placeholder="小区/标题/地址" clearable style="width: 220px;" />
            </el-form-item>

            <el-form-item label="城市">
              <el-select v-model="filters.city" placeholder="选择城市" clearable filterable style="width: 160px;">
                <el-option v-for="c in cities" :key="c" :label="c" :value="c" />
              </el-select>
            </el-form-item>

            <el-form-item label="价格">
              <el-input-number v-model="filters.priceMin" :min="0" :step="100" placeholder="最低" />
              <span class="range-sep">-</span>
              <el-input-number v-model="filters.priceMax" :min="0" :step="100" placeholder="最高" />
              <span class="unit">元/月</span>
            </el-form-item>

            <el-form-item label="面积">
              <el-input-number v-model="filters.areaMin" :min="0" :step="10" placeholder="最小" />
              <span class="range-sep">-</span>
              <el-input-number v-model="filters.areaMax" :min="0" :step="10" placeholder="最大" />
              <span class="unit">㎡</span>
            </el-form-item>

            <el-form-item label="排序">
              <el-select v-model="sortBy" style="width: 160px;">
                <el-option label="默认排序" value="default" />
                <el-option label="价格从低到高" value="price_asc" />
                <el-option label="价格从高到低" value="price_desc" />
                <el-option label="面积从大到小" value="area_desc" />
                <el-option label="最新发布" value="latest" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="fetchList(1)">搜索</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-row :gutter="16" class="list-grid">
          <el-col :span="8" v-for="item in list" :key="item.id">
            <el-card class="property-card" shadow="hover">
              <div class="thumb" :style="{ backgroundImage: `url(${item.cover || fallback})` }">
                <span class="badge new" v-if="isNew(item.created_at)">新上架</span>
                <span class="badge hot" v-else>热租</span>
              </div>
              <div class="info">
                <div class="title" :title="item.title">{{ item.title }}</div>
                <div class="meta">
                  <span>{{ item.city }} · {{ item.district || '热门区域' }}</span>
                  <span>{{ item.area }}㎡</span>
                </div>
                <div class="bottom">
                  <div class="price"><em>￥</em>{{ item.price }}<span>/月</span></div>
                  <el-button size="small" type="primary" text @click="goDetail(item.id)">查看</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-empty v-if="!list.length" description="暂无房源，试试调整筛选条件吧" class="empty-block" />

        <div class="pager" v-else>
          <el-pagination
            background
            layout="total, sizes, prev, pager, next"
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[6, 12, 24]"
            @current-change="(p) => fetchList(p)"
            @size-change="(s) => changeSize(s)"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { propertiesAPI } from '@/api/properties'

const router = useRouter()
const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都']
const fallback = 'https://picsum.photos/seed/house/600/400'

const filters = reactive({
  keyword: '',
  city: '',
  priceMin: undefined,
  priceMax: undefined,
  areaMin: undefined,
  areaMax: undefined,
})

const sortBy = ref('default')
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(12)

const mapSort = (value) => {
  switch (value) {
    case 'price_asc': return { sortField: 'price', sortOrder: 'asc' }
    case 'price_desc': return { sortField: 'price', sortOrder: 'desc' }
    case 'area_desc': return { sortField: 'area', sortOrder: 'desc' }
    case 'latest': return { sortField: 'created_at', sortOrder: 'desc' }
    default: return {}
  }
}

const fetchList = async (toPage = page.value) => {
  page.value = toPage
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    ...filters,
    ...mapSort(sortBy.value),
  }
  const res = await propertiesAPI.list(params)
  if (res?.success) {
    list.value = res.data.items
    total.value = res.data.total
  } else {
    list.value = res?.items || []
    total.value = res?.total || 0
  }
}

const resetFilters = () => {
  Object.assign(filters, {
    keyword: '',
    city: '',
    priceMin: undefined,
    priceMax: undefined,
    areaMin: undefined,
    areaMax: undefined,
  })
  sortBy.value = 'default'
  fetchList(1)
}

const changeSize = (size) => {
  pageSize.value = size
  fetchList(1)
}

const isNew = (createdAt) => {
  const now = Date.now()
  const ts = new Date(createdAt).getTime()
  return now - ts < 1000 * 60 * 60 * 24 * 7 // 7天内
}

const goDetail = (id) => {
  router.push(`/properties/${id}`)
}

onMounted(() => fetchList(1))
</script>

<style scoped>
.properties-page {
  min-height: 100vh;
  background: #f6f8fb;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 72px;
  padding: 8px 0;
}
.brand {
  display: flex;
  align-items: center;
  gap: 10px;
}
.brand-logo {
  width: 28px;
  height: 28px;
  border-radius: 4px;
}
.subtitle {
  color: #8c8c8c;
  font-size: 13px;
}

.filter-card {
  margin-bottom: 12px;
  border-radius: 10px;
}
.filter-form :deep(.el-form-item) {
  margin-bottom: 10px;
}
.range-sep {
  margin: 0 8px;
  color: #999;
}
.unit {
  margin-left: 6px;
  color: #999;
  font-size: 12px;
}

.list-grid {
  margin-top: 8px;
}

.property-card {
  margin-bottom: 16px;
  overflow: hidden;
  border-radius: 10px;
  transition: transform .2s ease, box-shadow .2s ease;
}
.property-card:hover {
  transform: translateY(-2px);
}

.thumb {
  position: relative;
  height: 172px;
  background-size: cover;
  background-position: center;
  border-radius: 8px;
}
.badge {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}
.badge.new { background: #52c41a; }
.badge.hot { background: #fa541c; }

.info {
  padding: 10px 4px 10px;
}
.title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.meta {
  color: #8c8c8c;
  font-size: 12px;
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}
.bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.price {
  color: #ff4d4f;
  font-weight: 700;
  font-size: 18px;
}
.price em {
  font-style: normal;
  font-size: 14px;
  margin-right: 1px;
}
.price span {
  color: #8c8c8c;
  font-weight: 400;
  font-size: 12px;
  margin-left: 4px;
}

.pager {
  display: flex;
  justify-content: center;
  margin: 16px 0 24px;
}

.empty-block {
  background: #fff;
  border-radius: 10px;
  padding: 40px 0;
  margin-top: 12px;
}
</style>